import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute} from '@angular/router';
import {CouponService} from '../coupon.service';
import {AliyunOssOutputUrl} from '../../../../config/api';
import {NzMessageService } from 'ng-zorro-antd';


import {
  FormBuilder,
  FormGroup,
} from '@angular/forms';
import {Observable} from 'rxjs/Observable';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.scss'],
  providers: [CouponService]
})


export class EditComponent implements OnInit {

  cardInfo;
  condition_receive_quantity;  // 可领取数量
  aliyunOssOutputUrl =   AliyunOssOutputUrl;
  validateForm: FormGroup;
  options = [];

  termOfValidity = true;
  inStockValidity = true;
  goodsValidity = true;
  checkedGoods = [];
  checkedGoodsTable = [];

  /* 添加商品弹框 */
  goodsModalVisible = false;
  goodsName: string;
  goodsList = [];
  groupList = [];
  allChecked = false;
  indeterminate = false;
  selectedGroup;  // 选中的商品分类
  page = 1;
  pageSize = 5;
  total;
  loading = false;
  id = null;

  constructor(private fb: FormBuilder,
              private router: Router,
              private route: ActivatedRoute,
              private couponService: CouponService,
              private _message: NzMessageService,
              ) {
    this.validateForm = this.fb.group({
    });
  }

  ngOnInit() {
    this.getCouponDetail();
    for (let i = 0; i < 61; i++) {
      this.options.push(i);
    }
  }

  // 添加商品
  addGoods() {
    this.goodsModalVisible = true;
    this.page = 1;
    this.checkedGoods = JSON.parse(JSON.stringify(this.checkedGoodsTable));
    this.getGoodsList();
  }

  // 获取所有商品列表
  getGoodsList() {
    this.loading = true;
    this.couponService.getGoodsList(this.page, this.pageSize, this.selectedGroup, this.goodsName,'上架').subscribe(res => {
      this.total = res.data.total;
      this.goodsList = res.data.data;
      if (!!this.goodsList.length) {
        this.goodsList.every((val, idx, array) => {
          if (!this.checkedGoods.length) {
            val.checked = false;
            return true;
          } else {
            this.checkedGoods.every((val1, idx1, array1) => {
              if (val.id === val1.id) {
                val.checked = true;
                return false;
              }
              return true;
            });
            return true;
          }
        });
      }
      this.loading = false;
      this.refreshStatus();
    });
  }

  // 搜索商品
  searchGoods() {
    this.page = 1;
    this.getGoodsList();
  }
  reset() {
    this.selectedGroup = null;
    this.goodsName  = '';
    this.page = 1;
    this.getGoodsList();
  }

  checkedSingle(event: any, data: any) {
    if (event) {
      this.checkedGoods.push(data);
    } else {
      this.checkedGoods.every((val, idx, array) => {
        if (data.id === val.id) {
          this.checkedGoods.splice(idx, 1);
          return false;
        }
        return true;
      });
    }
    this.refreshStatus();
  }

  checkAll(value) {
    if (value) {
      this.goodsList.every((val, idx, array) => {
        if (!val.checked) {
          val.checked = true;
          this.checkedGoods.push(val);
        }
        return true;
      });
    } else {
      this.goodsList.every((val, idx, array) => {
        if (val.checked) {
          val.checked = false;
          this.checkedGoods.every((val1, idx1, array1) => {
            if (val.id === val1.id) {
              this.checkedGoods.push(val);
              return false;
            }
            return true;
          });
        }
        return true;
      });
    }
    this.refreshStatus();
  }
  refreshStatus() {
    const allChecked = this.goodsList.every(value => value.checked === true);
    const allUnChecked = this.goodsList.every(value => !value.checked);
    this.allChecked = allChecked;
    this.indeterminate = (!allChecked) && (!allUnChecked);
  }

  pageChange() {
    this.getGoodsList();
  }

  confirmAddGoods() {
    this.checkedGoodsTable = this.checkedGoods;
    this.goodsModalVisible = false;
    this.goodsValidity = true;
  }

  delCheckedGoods(idx: number) {
    this.checkedGoodsTable.splice(idx, 1);
    this.checkedGoods = JSON.parse(JSON.stringify(this.checkedGoodsTable));
  }

  getCouponDetail() {
    const id = this.id = +this.route.snapshot.params['id'];
    this.couponService.getCouponDetail(id).subscribe(res => {
      this.cardInfo = res.data;
      this.condition_receive_quantity = res.data.condition_receive_quantity;
      if (this.cardInfo.condition_use_in === 3) {
        this.getGroupList();
      }
      if (this.cardInfo.condition_use_in === 2) {
        this.getGroupList();
        this.cardInfo.card_coupons_binding_use_in.every((val, idx, array) => {
          this.getGoodsDetail(val.third_party_relation_id);
          return true;
        });
      }
    });
  }

  getFormControl = (name) => {
    return this.validateForm.controls[name];
  }

  // 获取店铺商品类型列表
  getGroupList() {
    this.couponService.getGroupList().subscribe(res => {
      this.groupList = res.data.data;
      if (!!this.groupList.length) {
        this.groupList.every((val, idx, array) => {
          this.cardInfo.card_coupons_binding_use_in.every((val1, idx1, array1) => {
            if (val.id === val1.third_party_relation_id) {
              val.checked = true;
              return false;
            } else {
              val.checked = false;
            }
            return true;
          });
          return true;
        });
      }
    });
  }

  // 获取商品列表
  getGoodsDetail(id: number) {
    this.couponService.getGoodsDetail(id).subscribe(res => {
      const data = {};
      data['id'] = res.data.id;
      data['name'] = res.data.name;
      data['first_picture'] = res.data.first_picture;
      data['price'] = res.data.price / 1000;
      data['in_stock'] = res.data.in_stock;
      this.checkedGoodsTable.push(data);
    });
  }

  // 提交表单
  submitForm() {
    if (this.cardInfo.condition_use_in === 1) {
      this.cardInfo.relation_id_json = 0;
    } else if (this.cardInfo.condition_use_in === 2) {
      if (!!this.checkedGoodsTable.length) {
        const goods_id = [];
        this.checkedGoodsTable.every((val, idx, array) => {
          goods_id.push(val.id);
          return true;
        });
        this.cardInfo.relation_id_json = JSON.stringify(goods_id);
      } else {
        this.goodsValidity = false;
        return;
      }
    } else {
      const category_id = [];
      this.groupList.every((val, idx, array) => {
        if (val.checked) {
          category_id.push(val.id);
        }
        return true;
      });
      if (!category_id.length) {
        this.goodsValidity = false;
        return;
      } else {
        this.cardInfo.relation_id_json = JSON.stringify(category_id);
      }
    }
    this.couponService.editCoupon(this.cardInfo.id, this.condition_receive_quantity, this.cardInfo.relation_id_json).subscribe(res => {
      if (res.code === 2000) {
        this._message.create('success', `卡券修改成功`);
        this.router.navigate(['member/coupon/list']);
      } else {
        this._message.create('error', res.message);
      }
    });
  }
}
